#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->label->setText("edit the list");
    ui->label->setAlignment(Qt::AlignCenter);

    ui->pushButton_add->setText("add");
    ui->pushButton_del->setText("del");

    ui->listWidget->addItem("C++");
    ui->listWidget->addItem("Java");
    ui->listWidget->addItem("go");

    ui->lineEdit->setPlaceholderText("enter added item");
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_add_clicked()
{
    if(ui->lineEdit->text().isEmpty())
        return ;
    int row = ui->listWidget->currentRow();
    ui->listWidget->insertItem(row,ui->lineEdit->text().trimmed());
    ui->lineEdit->clear();
}

void Widget::on_pushButton_del_clicked()
{
    if(!ui->listWidget->count())
    {
        ui->lineEdit->clear();
        return ;
    }
    if(ui->lineEdit->text().isEmpty())
    {
        int row = ui->listWidget->currentRow();
        ui->listWidget->takeItem(row);
    }
    else
    {
        const QString& delItem =ui->lineEdit->text().trimmed();
        int num = ui->listWidget->count();
        for(int i = 0;i<num;i++)
        {
            QListWidgetItem* item = ui->listWidget->item(i);
            if(item->text() == delItem)
            {
                ui->listWidget->takeItem(i);
                break;
            }
        }
        ui->lineEdit->clear();
    }
}

void Widget::on_listWidget_currentTextChanged(const QString &currentText)
{
   (void)currentText;
}

void Widget::on_listWidget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    if(current)
        qDebug() << "current item: " + current->text();
    if(previous)
        qDebug() << "previous item: " + previous->text();
    qDebug() << "#################";
}
